package instrumentation

import (
	"context"
	"go.opentelemetry.io/otel/exporters/otlp/otlpmetric"
	"go.opentelemetry.io/otel/metric"
	"go.opentelemetry.io/otel/metric/global"
	sdkmcontroller "go.opentelemetry.io/otel/sdk/metric/controller/basic"
	sdkmprocessor "go.opentelemetry.io/otel/sdk/metric/processor/basic"
	"go.opentelemetry.io/otel/sdk/metric/selector/simple"
	"go.opentelemetry.io/otel/sdk/resource"
	metricpb "go.opentelemetry.io/proto/otlp/metrics/v1"
	"log"
)

var controller *sdkmcontroller.Controller
var Meter metric.Meter

type CustomClient struct {
	otlpmetric.Client
}

func (c *CustomClient) UploadMetrics(ctx context.Context, protoMetrics []*metricpb.ResourceMetrics) error {

	for _, m := range protoMetrics {
		log.Printf("%+v\n", m)
	}

	return nil
}

func (c *CustomClient) Start(ctx context.Context) error {
	return nil
}

func (c *CustomClient) Stop(ctx context.Context) error {
	return nil
}

func init() {
	var err error
	controller, err = NewController(context.Background())

	if err != nil {
		return
	}

	Meter = controller.Meter("test")
}

func NewController(ctx context.Context) (*sdkmcontroller.Controller, error) {

	r, _ := resource.New(context.Background())

	//exporter, _ := stdoutmetric.New(
	//	stdoutmetric.WithPrettyPrint(),
	//)

	client := &CustomClient{}

	otlpExporter, err := otlpmetric.New(context.Background(), client)
	if err != nil {
		return nil, err
	}

	controller := sdkmcontroller.New(
		sdkmprocessor.NewFactory(simple.NewWithHistogramDistribution(), otlpExporter),
		sdkmcontroller.WithExporter(otlpExporter),
		sdkmcontroller.WithResource(r),
	)

	global.SetMeterProvider(controller)

	err = controller.Start(ctx)
	if err != nil {
		return nil, err
	}

	return controller, nil
}
